package com.atguigu.gulimall.ware.listener;

import com.atguigu.common.to.mq.OrderTo;
import com.atguigu.common.to.mq.StockLockedTo;
import com.atguigu.gulimall.ware.service.WareSkuService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

import static com.atguigu.gulimall.ware.config.RabbitMqConfig.STOCK_RELEASE_QUEUE;

/**
 * Rabbit库存解锁的消费者；
 * 接收库存交换机发送的延迟消息，解锁库存
 *
 * @Author ShiJieLin
 * @Date 2022/5/1 23:12
 * @Version 1.0
 */
@RabbitListener(queues = {STOCK_RELEASE_QUEUE})
@Slf4j
@Component
public class StockReleaseListener {

    @Autowired
    private WareSkuService wareSkuService;

    /** 1.库存自动解锁
     *    下订单成功，库存锁定成功，接下来的业务调用失败，导致订单回滚。之前锁定的库存就要自动解锁
     *  2.订单失败
     *    库存锁定失败
     *  如果解锁失败，那么需要将消息重新放入队列
     * @param to 订单锁定的详细信息
     * @param message
     * @param channel
     * @throws IOException
     */
    @RabbitHandler
    public void handleStockLockedRelease(StockLockedTo to,
                                         Message message,
                                         Channel channel) throws IOException {

        log.info("******收到解锁库存的信息******");
        try {
            //当前消息是否被第二次及以后（重新）派发过来了
            // Boolean redelivered = message.getMessageProperties().getRedelivered();
            //解锁库存
            wareSkuService.unlockStock(to);
            // 手动删除消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (Exception e) {
            // 解锁失败 将消息重新放回队列，让别人消费
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }
    }

    /** 订单如果是被取消的状态，解锁库存,
     * @param orderTo 订单详细
     * @param message
     * @param channel
     * @throws IOException
     */
    @RabbitHandler
    public void handleStockLockedRelease(OrderTo orderTo,
                                         Message message,
                                         Channel channel) throws IOException {
        log.info("******订单被取消，解锁库存******");
        try {
            // 解锁库存
            wareSkuService.unlockStock(orderTo);
            // 手动删除消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (Exception e) {
            // 解锁失败 将消息重新放回队列，让别人消费
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }
    }

}
